﻿namespace Hidistro.SaleSystem.Member
{
    using Hidistro.Core.Entities;
    using Hidistro.Entities.Commodities;
    using Hidistro.Entities.Members;
    using Hidistro.Entities.Orders;
    using Hidistro.Entities.Promotions;
    using Hidistro.Entities.Sales;
    using Hidistro.Membership.Context;
    using Hidistro.Membership.Core;
    using Hidistro.Membership.Core.Enums;
    using Hidistro.SqlDal;
    using Hidistro.SqlDal.Commodities;
    using Hidistro.SqlDal.Members;
    using Hidistro.SqlDal.Orders;
    using Hidistro.SqlDal.Promotions;
    using Hidistro.SqlDal.Sales;
    using Juse.Interface;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Runtime.InteropServices;

    public static class TradeHelper
    {
        public static int AddClaimCodeToUser(string claimCode, int userId)
        {
            return new CouponDao().AddClaimCodeToUser(claimCode, userId);
        }

        public static bool ApplyForRefund(string orderId, string remark, int refundType)
        {
            return new RefundDao().ApplyForRefund(orderId, remark, refundType);
        }

        public static bool ApplyForReplace(string orderId, string remark)
        {
            return new ReplaceDao().ApplyForReplace(orderId, remark);
        }

        public static bool ApplyForReturn(string orderId, string remark, int refundType)
        {
            return new ReturnDao().ApplyForReturn(orderId, remark, refundType);
        }

        public static bool CanRefund(string orderId)
        {
            return new RefundDao().CanRefund(orderId);
        }

        public static bool CanReplace(string orderId)
        {
            return new ReplaceDao().CanReplace(orderId);
        }

        public static bool CanReturn(string orderId)
        {
            return new ReturnDao().CanReturn(orderId);
        }

        public static bool CloseOrder(string orderId)
        {
            OrderDao dao = new OrderDao();
            OrderInfo orderInfo = dao.GetOrderInfo(orderId);
            if (orderInfo.CheckAction(OrderActions.SELLER_CLOSE))
            {
                orderInfo.OrderStatus = OrderStatus.Closed;
                return dao.UpdateOrder(orderInfo, null);
            }
            return false;
        }

        public static bool ConfirmOrderFinish1(OrderInfo order)
        {
            bool flag = false;
            if (order.CheckAction(OrderActions.BUYER_CONFIRM_GOODS))
            {
                order.OrderStatus = OrderStatus.Finished;
                order.PayDate = DateTime.Now;
                order.FinishDate = DateTime.Now;
                flag = new OrderDao().UpdateOrder(order, null);
            }
            return flag;
        }
        public static bool ConfirmOrderFinish(JSShop.Model.OrderInfo order)
        {
            bool flag = false;
            OrderInfo orders = new OrderInfo();
            if (orders.CheckAction(OrderActions.BUYER_CONFIRM_GOODS))
            {
                order.OrderStatus = JSShop.Enum.OrderStatus.Finished;
                order.PayDate = DateTime.Now;
                order.FinishDate = DateTime.Now;
                flag = new OrderInterface().UpdateOrderPaySuccess(order);
            }
            return flag;
        }

        public static bool ExitCouponClaimCode(string claimCode)
        {
            return new CouponDao().ExitCouponClaimCode(claimCode);
        }

        public static DataTable GetChangeCoupons()
        {
            return new CouponDao().GetChangeCoupons();
        }

        public static CountDownInfo GetCountDownBuy(int CountDownId)
        {
            return new CountDownDao().GetCountDownInfo(CountDownId);
        }

        public static GroupBuyInfo GetGroupBuy(int groupBuyId)
        {
            return new GroupBuyDao().GetGroupBuy(groupBuyId);
        }

        public static int GetOrderCount(int groupBuyId)
        {
            return new GroupBuyDao().GetOrderCount(groupBuyId);
        }

        public static OrderInfo GetOrderInfo(string orderId)
        {
            return new OrderDao().GetOrderInfo(orderId);
        }

        public static DataSet GetOrderGoods(string orderIds)
        {
            return new OrderDao().GetOrderGoods(orderIds);
        }

        public static DataSet GetOrderGoodsNew(string orderIds)
        {
            return new OrderDao().GetOrderGoodsNew(orderIds);
        }
        /// <summary>
        /// 获取支付方式
        /// </summary>
        /// <param name="modeId"></param>
        /// <returns></returns>
        public static PaymentModeInfo GetPaymentMode(int modeId)
        {
            return new PaymentModeDao().GetPaymentMode(modeId);
        }

        public static IList<PaymentModeInfo> GetPaymentModes(PayApplicationType payApplicationType)
        {
            return new PaymentModeDao().GetPaymentModes(payApplicationType);
        }

        public static DbQueryResult GetRefundApplys(RefundApplyQuery query)
        {
            return new RefundDao().GetRefundApplys(query);
        }

        public static decimal GetRefundMoney(OrderInfo order, out decimal refundMoney)
        {
            return new ReturnDao().GetRefundMoney(order, out refundMoney);
        }

        public static DbQueryResult GetReplaceApplys(ReplaceApplyQuery query)
        {
            return new ReplaceDao().GetReplaceApplys(query);
        }

        public static DbQueryResult GetReturnsApplys(ReturnsApplyQuery query)
        {
            return new ReturnDao().GetReturnsApplys(query);
        }

        public static DataTable GetUserCoupons(int userId)
        {
            return new CouponDao().GetUserCoupons(userId, 0);
        }

        public static DbQueryResult GetUserOrder(int userId, OrderQuery query)
        {
            return new OrderDao().GetMyUserOrder(userId, query);
        }

        public static DbQueryResult GetUserOrder(int userId, OrderQuery query,string sql)
        {
            return new OrderDao().GetMyUserOrder(userId, query,sql);
        }

        public static DbQueryResult GetUserPoints(int pageIndex)
        {
            return new PointDetailDao().GetUserPoints(pageIndex);
        }

        public static bool PointChageCoupon(int couponId, int needPoint, int currentPoint)
        {
            Member user = HiContext.Current.User as Member;
            PointDetailInfo point = new PointDetailInfo {
                OrderId = string.Empty,
                UserId = user.UserId,
                TradeDate = DateTime.Now,
                TradeType = PointTradeType.ChangeCoupon,
                Increased = null,
                Reduced = new int?(needPoint),
                Points = currentPoint - needPoint
            };
            if ((point.Points >= 0) && new PointDetailDao().AddPointDetail(point))
            {
                CouponItemInfo couponItem = new CouponItemInfo {
                    CouponId = couponId,
                    UserId = new int?(user.UserId),
                    UserName = user.Username,
                    EmailAddress = user.Email,
                    ClaimCode = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 15),
                    GenerateTime = DateTime.Now
                };
                Users.ClearUserCache(user);
                if (new CouponDao().SendClaimCodes(couponItem))
                {
                    return true;
                }
            }
            return false;
        }

        public static int RemoveOrder(string orderIds)
        {
            return new OrderDao().DeleteOrders(orderIds);
        }

        public static bool SaveDebitNote(DebitNoteInfo note)
        {
            return new DebitNoteDao().SaveDebitNote(note);
        }

        public static bool SetGroupBuyEndUntreated(int groupBuyId)
        {
            return new GroupBuyDao().SetGroupBuyEndUntreated(groupBuyId);
        }

        public static bool UpdateOrderPaymentType(OrderInfo order)
        {
            return (order.CheckAction(OrderActions.SELLER_MODIFY_TRADE) && new OrderDao().UpdateOrder(order, null));
        }

        //public static bool UserPayOrder(OrderInfo order, bool isBalancePayOrder)
        //{
        //    order.OrderStatus = OrderStatus.BuyerAlreadyPaid;
        //    OrderDao dao = new OrderDao();
        //    if (order.UserId == 1100)
        //    {
                
        //      bool  aa = dao.UpdateOrder(order, null);
        //      return aa;
        //    }
        //    else
        //    {
        //        bool flag = false;
              
               
        //        order.PayDate = DateTime.Now;
        //        flag = dao.UpdateOrder(order, null);
        //        if (flag)
        //        {
        //            //decimal num;
        //            //BalanceDetailInfo info;//预付款明细表操作
        //            //Member member = Users.GetUser(order.UserId, false) as Member;
        //            //BalanceDetailDao dao2 = new BalanceDetailDao();
        //            //if (isBalancePayOrder && (member != null))
        //            //{
        //            //    num = member.Balance - order.GetTotal();
        //            //    info = new BalanceDetailInfo
        //            //    {
        //            //        UserId = order.UserId,
        //            //        UserName = order.Username,
        //            //        TradeDate = DateTime.Now,
        //            //        TradeType = TradeTypes.Consume,
        //            //        Expenses = new decimal?(order.GetTotal()),
        //            //        Balance = num,
        //            //        Remark = string.Format("对订单{0}付款", order.OrderId)
        //            //    };
        //            //    dao2.InsertBalanceDetail(info);
        //            //}
        //            dao.UpdatePayOrderStock(order.OrderId);//
        //            ProductDao dao3 = new ProductDao();
        //            foreach (LineItemInfo info2 in order.LineItems.Values)
        //            {
        //                ProductInfo productDetails = dao3.GetProductDetails(info2.ProductId);
        //                productDetails.SaleCounts += info2.Quantity;
        //                productDetails.ShowSaleCounts += info2.Quantity;
        //                dao3.UpdateProduct(productDetails, null);//
        //            }
        //            if ((order.UserId == 0) || (order.UserId == 0x44c))
        //            {
        //                return flag;
        //            }
        //            IUser user = Users.GetUser(order.UserId, false);//
        //            if ((user == null) || (user.UserRole != UserRole.Member))
        //            {
        //                return flag;
        //            }
        //            //PointDetailDao dao4 = new PointDetailDao();
        //            //PointDetailInfo point = new PointDetailInfo
        //            //{
        //            //    OrderId = order.OrderId,
        //            //    UserId = member.UserId,
        //            //    TradeDate = DateTime.Now,
        //            //    TradeType = PointTradeType.Bounty,
        //            //    Increased = new int?(order.Points),
        //            //    Points = order.Points + member.Points
        //            //};
        //            //if ((point.Points > 0x7fffffff) || (point.Points < 0))
        //            //{
        //            //    point.Points = 0x7fffffff;
        //            //}
        //            //dao4.AddPointDetail(point);//积分详细操作
        //            //int referralDeduct = HiContext.Current.SiteSettings.ReferralDeduct;
        //            //if (((referralDeduct > 0) && member.ReferralUserId.HasValue) && (member.ReferralUserId.Value > 0))
        //            //{
        //            //    IUser user2 = Users.GetUser(member.ReferralUserId.Value, false);
        //            //    if ((user2 != null) && (user2.UserRole == UserRole.Member))
        //            //    {
        //            //        Member member2 = user2 as Member;
        //            //        if ((member.ParentUserId == member2.ParentUserId) && member2.IsOpenBalance)
        //            //        {
        //            //            num = member2.Balance + ((order.GetTotal() * referralDeduct) / 100M);
        //            //            info = new BalanceDetailInfo
        //            //            {
        //            //                UserId = member2.UserId,
        //            //                UserName = member2.Username,
        //            //                TradeDate = DateTime.Now,
        //            //                TradeType = TradeTypes.ReferralDeduct,
        //            //                Income = new decimal?((order.GetTotal() * referralDeduct) / 100M),
        //            //                Balance = num,
        //            //                Remark = string.Format("提成来自'{0}'的订单{1}", order.Username, order.OrderId)
        //            //            };
        //            //            dao2.InsertBalanceDetail(info);
        //            //        }
        //            //    }
        //            //}
        //            //MemberDao dao5 = new MemberDao();
        //            //dao5.UpdateMemberAccount(order.GetTotal(), order.UserId);
        //            //int historyPoint = dao4.GetHistoryPoint(member.UserId);
        //            //dao5.ChangeMemberGrade(member.UserId, member.GradeId, historyPoint);
        //            Users.ClearUserCache(user);
        //        }
        //        return flag;
        //    }
           
        //}
        public static bool UserPayOrder(JSShop.Model.OrderInfo order, bool isBalancePayOrder)
        {
            //order.OrderStatus = JSShop.Enum.OrderStatus.BuyerAlreadyPaid;
            order.IsAlreadyPay = 1;
            order.PayDate = DateTime.Now;
            order.FinishDate = DateTime.Now;
            //OrderDao dao = new OrderDao();
            if (order.UserId == 1100)
            {

                //bool aa = new OrderInterface().UpdateOrderPaySuccess(order);
                bool aa = new OrderInterface().UpdateOrderPaySuccessStatus(order);
                return aa;
            }
            else
            {
                bool flag = false;


                order.PayDate = DateTime.Now;
                //flag = new OrderInterface().UpdateOrderPaySuccess(order);
                flag = new OrderInterface().UpdateOrderPaySuccessStatus(order);
                if (flag)
                {
                    //dao.UpdatePayOrderStock(order.OrderId);//
                    //ProductDao dao3 = new ProductDao();
                    foreach (JSShop.Model.Hishop_OrderItems info2 in order.LineItems.Values)
                    {
                        JSShop.Model.Hishop_Products productDetails = new JSShop.Model.Hishop_Products();
                        productDetails = new ProductBrowser().GetProductInfo(info2.ProductId);
                        productDetails.SaleCounts += info2.Quantity;
                        productDetails.ShowSaleCounts += info2.Quantity;
                        new ProductBrowser().SetProductInfo(productDetails);
                    }
                    if ((order.UserId == 0) || (order.UserId == 0x44c))
                    {
                        return flag;
                    }
                    JSShop.Model.aspnet_Users user = new JSShop.Model.aspnet_Users();
                    user = new UserProcessor().GetUser(order.Username);
                    if ((user == null))
                    {
                        return flag;
                    }
                }
                return flag;
            }

        }
    }
}

